import { defineModel } from 'foca';

import { memberInterface } from '@/apis';
import { tools } from '@/utils';

export interface UserState {
	isLogin: boolean;
	token?: string;
	memberInfo?: any;
}

const initialState: UserState = {
	isLogin: false,
	token: undefined,
	memberInfo: undefined,
};

export const userModel = defineModel('user', {
	initialState,
	computed: {
		accountPhone() {
			// 有手机号取手机号，否则取账号
			const { account, phone } = this.state.memberInfo || {};
			return phone ? phone : account;
		},
	},
	reducers: {
		updateMemberInfo(state, memberInfo: UserState['memberInfo'] & { showDownload?: boolean }) {
			if (!memberInfo) return;
			state.isLogin = true;
			state.memberInfo = memberInfo;
			if (memberInfo.accessToken) state.token = memberInfo.accessToken;
		},

		clear(state) {
			return {
				...initialState,
			};
		},
	},
	methods: {
		async fetchUserInfo() {
			// await withdrawInterface.homeWithdraw()
			const { data, isSuccess } = await memberInterface.memberInfo();
			if (isSuccess && data) {
				try {
				} catch (error) {
					this.updateMemberInfo(data);
				}
			} else {
				this.clear();
			}
		},
	},
	events: {
		async onInit() {
			if (!this.state.isLogin) return;
			await this.fetchUserInfo();
		},
		async onChange(prevState, nextState) {
			if (nextState.isLogin && prevState.isLogin !== nextState.isLogin) {
				// 登录状态改变且已经登录
				await this.fetchUserInfo();
			}
			if (prevState.isLogin !== nextState.isLogin && !nextState.isLogin) {
				// 退出登录
			}
		},
	},
});
